﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Data;
using DBA.Common;
using DBA.Data;
using DBA.Data.ADO;
using DBA.Model;
using System.Data.SqlClient;

namespace DBA.Web.SystemManage.Permissions
{
    public partial class RolePermission : System.Web.UI.Page
    {
        List<Sys_SystemFunction> userFuncList = new List<Sys_SystemFunction>();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //BindSys();
                hidRoleID.Value = RequestHelper.QueryString("id");
                userFuncList = GetRoleFunction(ConvertHelper.ToInt32(hidRoleID.Value));
                getUserTree();
                foreach (Sys_SystemFunction func in userFuncList)
                {
                    hidFunIDList.Value += "," + func.FuncID.ToString();
                }
            }
        }

        DataAccessLibrary dal = CommonQuery.DataAccessLibrary;


        /// <summary>
        /// 获取角色下单个子系统的所有权限菜单
        /// </summary>
        /// <param name="BelongSystem">子系统标识</param>
        /// <param name="roleGuid">角色ID</param>
        /// <returns>List<Sys_SystemFunction></returns>
        private List<Sys_SystemFunction> GetRoleFunction(int roleID)
        {
            List<Sys_SystemFunction> funcList = new List<Sys_SystemFunction>();

            string strSelect = "SELECT a.FuncID,a.ParentFuncID,a.FuncName,a.FuncType,a.FuncUrl,a.FuncRemark";
            strSelect += " FROM Sys_SystemFunction a INNER JOIN Sys_RoleAndFunc b ON a.FuncID=b.FuncID";
            strSelect += " WHERE b.RoleID=@RoleID";

            dal.ManagerParameter.ClearParameter();
            dal.ManagerParameter.AddNewInParameter("RoleID", roleID);

            DataTable dt = dal.ExecuteFillDataTable(strSelect);

            foreach (DataRow dr in dt.Rows)
            {
                Sys_SystemFunction func = new Sys_SystemFunction();
                func.FuncID = ConvertHelper.ToInt32(dr["FuncID"]);
                func.FuncName = dr["FuncName"].ToString();
                func.FuncRemark = dr["FuncRemark"].ToString();
                func.FuncType = ConvertHelper.ToInt16(dr["FuncType"]);
                func.FuncUrl = dr["FuncUrl"].ToString();
                if (dr["ParentFuncID"].ToString() != "")
                {
                    func.ParentFuncID = ConvertHelper.ToInt32(dr["ParentFuncID"]);
                }

                funcList.Add(func);
            }

            return funcList;

        }
        /// <summary>
        /// 得到用户树
        /// </summary>
        protected void getUserTree()
        {
            Sys_SystemFunction funBll = new Sys_SystemFunction();

            List<TreeNode> treeNodeList = new List<TreeNode>();

            TreeNode tree0 = new TreeNode();
            tree0.id = "1";
            tree0.name = "角色所有权限";
            tree0.pId = "0";
            treeNodeList.Add(tree0);

            foreach (Sys_SystemFunction fun in userFuncList)
            {
                TreeNode node = new TreeNode();
                node.id = fun.FuncID.ToString();
                node.name = fun.FuncName;
                node.pId = fun.ParentFuncID.ToString();
                treeNodeList.Add(node);
            }

            hidJsonTree.Value = JsonConvert.SerializeObject(treeNodeList);
        }



        protected void lnkSave_Click(object sender, EventArgs e)
        {
            int t = userFuncList.Count;
            string strFunc = hidFunIDList.Value.TrimStart(',');
            //BSysPageNode funBll = new BSysPageNode();
            //if (hidRoleID.Value == "1")
            //{
            //    hdResult.Value = "-1";
            //}
            //else
            //{
                if (SaveRoleFunc(hidRoleID.Value, strFunc))
                {
                    hdResult.Value = "1";
                }
                else
                {
                    hdResult.Value = "0";
                }
            //}
        }

        /// <summary>
        /// 将结果保存的角色功能表中
        /// </summary>
        /// <param name="roleID">角色ID</param>
        /// <param name="func">功能ID字符串</param>
        /// <returns></returns>
        private bool SaveRoleFunc(string roleID, string func)
        {
            bool flag = false;
            string[] funcList = func.Split(',');
            
            //DataTable dt = new DataTable();
            ////dt.Columns.Add("NodeSGuid", System.Type.GetType("System.Int32"));
            //dt.Columns.Add("RoleID", System.Type.GetType("System.Int32"));
            //dt.Columns.Add("FuncID", System.Type.GetType("System.Int32"));

            dal.ManagerTran.TranBegin();

            try
            {
                string sql = "DELETE  FROM Sys_RoleAndFunc WHERE RoleID = @RoleID";
                dal.ManagerParameter.ClearParameter();
                dal.ManagerParameter.AddNewInParameter("RoleID", roleID);
                dal.ExecuteNonQuery(sql);

                foreach (string strFunc in funcList)
                {
                    //DataRow dr = dt.NewRow();
                    ////dr["NodeSGuid"] = System.Guid.NewGuid();
                    //dr["RoleID"] = ConvertHelper.ToInt32(roleID);
                    //dr["FuncID"] = ConvertHelper.ToInt32(strFunc);
                    //dt.Rows.Add(dr);
                    string strInsertRole = "insert into Sys_RoleAndFunc(RoleID,FuncID) values (@RoleID,@FuncID) ";
                    dal.ManagerParameter.ClearParameter();
                    dal.ManagerParameter.AddNewInParameter("RoleID", roleID);
                    dal.ManagerParameter.AddNewInParameter("FuncID", strFunc);
                    dal.ExecuteNonQuery(strInsertRole);
                }

                dal.ManagerTran.TranCommit();
                flag = true;
            }

          
            
            //dal.ManagerTran.TranBegin();
            //try
            //{
            //    string sql = "DELETE  FROM Sys_RoleAndFunc WHERE RoleID = @RoleID";
            //    dal.ManagerParameter.ClearParameter();
            //    dal.ManagerParameter.AddNewInParameter("RoleID", roleID);
            //    dal.ExecuteNonQuery(sql);
            //    using (SqlBulkCopy bcp = new SqlBulkCopy((SqlConnection)dal.Command.Connection, SqlBulkCopyOptions.Default,
            //                                   (SqlTransaction)dal.Command.Transaction))
            //    {
            //        try
            //        {
            //            bcp.BatchSize = 1000;
            //            bcp.BulkCopyTimeout = 120;
            //            bcp.DestinationTableName = "Sys_RoleAndFunc";
            //            bcp.ColumnMappings.Add("RoleID", "RoleID");
            //            bcp.ColumnMappings.Add("FuncID", "FuncID");
            //            bcp.WriteToServer(dt);
            //        }
            //        catch
            //        {
            //            throw;
            //        }
            //    }
            //    dal.ManagerTran.TranCommit();
            //    flag = true;
            //}
            catch
            {
                dal.ManagerTran.TranRollBack();
            }

            return flag;
        }


    }
    public class TreeNode
    {
        public string id;
        public string name;
        public string pId;
    }

}